/**
 * Copyright (c) 2016, 2024, All rights reserved.
 * Powered by [liangyafeng@duplicall.com] On 2024-03-21 16:12:35
 */
package com.yafengliang.controller;


import lombok.extern.slf4j.Slf4j;

import javax.sound.sampled.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p>Project: SpringBoot - RecordAudio
 * <p>@author liangyafeng@duplicall.com On 2024-03-21 16:12:35
 *
 * @Description
 */
@Slf4j
public class RecordAudio {


    private TargetDataLine targetDataLine;
    private boolean isRecording;

    public void startRecording() {
        isRecording = true;
        try {
            AudioFormat audioFormat = new AudioFormat(
                    44100,
                    16,
                    1,
                    true,
                    true);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
            if (!AudioSystem.isLineSupported(info)) {
                System.out.println("麦克风不支持！");
                return;
            }
            targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
            targetDataLine.open(audioFormat);
            targetDataLine.start();
            log.info("Start Recording ... ... ");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int bufferSize = 3200;
            byte[] buffer = new byte[bufferSize];

            for (int i = 10; i >= 1; i--) {
                int count = targetDataLine.read(buffer, 0, buffer.length);
                if (count > 0) {
                    out.write(buffer, 0, count);
                }
            }

            targetDataLine.stop();
            targetDataLine.close();

            byte[] audioData = out.toByteArray();
            saveRecording(audioData);
        } catch (LineUnavailableException e) {
            log.error("{}", e.toString());
        }
    }

    private void saveRecording(byte[] audioData) {
        try {
            String fileName = "recording.wav";
            FileOutputStream fos = new FileOutputStream(fileName);
            fos.write(audioData);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            stopRecording();
        }
    }

    public void stopRecording() {
        try {
            targetDataLine.stop();
            targetDataLine.close();
            log.info("Stop Recording ... ... ");
        } catch (Exception e) {
            log.error("{}", e.toString());
        }
    }


    public static void main(String[] args) {
        RecordAudio recordAudio = new RecordAudio();
        recordAudio.startRecording();
        try {
            Thread.sleep(10 * 1000);
        }catch (InterruptedException e){
            log.error("{}",e.toString());
        }
        recordAudio.stopRecording();
    }


}
